package com.portico.security

import org.apache.commons.lang.builder.HashCodeBuilder

class UserAuthority implements Serializable {

	User person
	Authority authority

	boolean equals(other) {
		if (!(other instanceof UserAuthority)) {
			return false
		}

		other.person?.id == person?.id &&
			other.authority?.id == authority?.id
	}

	int hashCode() {
		def builder = new HashCodeBuilder()
		if (person) builder.append(person.id)
		if (authority) builder.append(authority.id)
		builder.toHashCode()
	}

	static UserAuthority get(long personId, long authorityId) {
		find 'from UserAuthority where person.id=:personId and authority.id=:authorityId',
			[personId: personId, authorityId: authorityId]
	}

	static UserAuthority create(User person, Authority authority, boolean flush = false) {
      if ( UserAuthority.findByAuthorityAndPerson(authority, person)== null )
		new UserAuthority(person: person, authority: authority).save(flush: flush, insert: true)
	}

	static boolean remove(User person, Authority authority, boolean flush = false) {
		UserAuthority instance = UserAuthority.findByPersonAndAuthority(person, authority)
		if (!instance) {
			return false
		}

		instance.delete(flush: flush)
		true
	}

	static void removeAll(User person) {
		executeUpdate 'DELETE FROM UserAuthority WHERE person=:person', [person: person]
	}

	static void removeAll(Authority authority) {
		executeUpdate 'DELETE FROM UserAuthority WHERE authority=:authority', [authority: authority]
	}

	static mapping = {
		id composite: ['authority', 'person']
		version false
	}
}
